package com.ruoyi.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.entity.dto.ChatRequest;
import com.ruoyi.entity.dto.KnowledgeBase;
import com.ruoyi.service.LlmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient;

import javax.annotation.Resource;

@Api(tags = "LLM知识库管理")
@RestController
@RequestMapping("/api/llm")
public class LlmController {

    @Value("${anythingllm.base-url}")
    private String baseUrl;

    @Value("${anythingllm.api-key}")
    private String apiKey;

    @Resource
    private LlmService llmService;

    private final WebClient webClient = WebClient.create();

    @ApiOperation("获取所有知识库")
    @GetMapping("/knowledgeBases")
    public R getKnowledgeBases() {
        // 调用 AnythingLLM 的 GET /v1/workspaces 接口
        String response = webClient.get()
                .uri(baseUrl + "/v1/workspaces")
                .header("Authorization", "Bearer " + apiKey)
                .retrieve()
                .bodyToMono(String.class)
                .block();

        System.out.println("获取所有知识库res:      "+   response);
        return R.ok(response);
    }

    @PostMapping("/createKnowledgeBase")
    public R createKnowledgeBase(@RequestBody KnowledgeBase knowledgeBase) {
        return R.ok(llmService.createKnowledgeBase(knowledgeBase));
    }

    @PostMapping("/uploadDocument")
    public R uploadDocument(@RequestParam("file") MultipartFile file,
                            @RequestParam String workspaceSlug) {
        return R.ok(llmService.uploadDocument(file, workspaceSlug));
    }

    @PostMapping("/chat")
    public R chat(@RequestBody ChatRequest request) {
        System.out.println("回复的消息:     "+ request);
        return R.ok(llmService.chat(request));
    }
}
